﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;

namespace Al_FrameWork
{
    public class CheckUpdateManager : MonoBehaviour
    {
        private static CheckUpdateManager _instance;

        public static CheckUpdateManager Instance
        {
            get { return GlobalFunctions.GetInstance(ref _instance, "_CheckUpdateManager", true); }
        }

        /// <summary>
        /// 比较文件名字
        /// </summary>
        private const string remoteABCompareName = "ABCompareInfo.txt";

        /// <summary>
        /// 需要下载的总大小
        /// </summary>
        private long needDownLoadSize;

        /// <summary>
        /// 需要下载的总文件个数
        /// </summary>
        private int needDownLoadCount;

        /// <summary>
        /// 热更服务器信息
        /// </summary>
        private Dictionary<string, ABInfo> serverABInfos;

        /// <summary>
        /// 本地AB信息
        /// </summary>
        private Dictionary<string, ABInfo> localABInfo;

        /// <summary>
        /// 需要下载的ab
        /// </summary>
        private List<ABInfo> needDownloadAB;

        /// <summary>
        /// 需要下载的总大小
        /// </summary>
        /// <returns></returns>
        public long NeedDownLoadTotalSize()
        {
            return needDownLoadSize;
        }

        /// <summary>
        /// 需要下载文件的个数
        /// </summary>
        /// <returns></returns>
        public int NeedDownLoadFileCounts()
        {
            return needDownLoadCount;
        }


        /// <summary>
        /// 开始
        /// </summary>
        public void CheckUpdate()
        {
            needDownloadAB.Clear();
            serverABInfos.Clear();
            localABInfo.Clear();
            needDownLoadSize = 0;
            needDownLoadCount = 0;
            string remoteABPath = GlobalFunctions.GetPersistentDataPath(GameConfig.ABCompareTempInfo);
            string localABPath = GlobalFunctions.GetPersistentDataPath(GameConfig.ABCompareInfo);
            //本地比对文件是否存在
            if (File.Exists(localABPath))
            {
                string[] remoteABInfos = File.ReadAllLines(remoteABPath);
                string[] localABInfos = File.ReadAllLines(localABPath);
                foreach (string remoteABInfoStr in remoteABInfos)
                {
                    if (string.IsNullOrEmpty(remoteABInfoStr) || string.IsNullOrWhiteSpace(remoteABInfoStr))
                    {
                        continue;
                    }

                    string[] array = remoteABInfoStr.Split('|');
                    ABInfo abInfo = new ABInfo();
                    abInfo.RelativePath = array[0];
                    abInfo.Md5 = array[1];
                    abInfo.Size = long.Parse(array[2]);
                    abInfo.FileName = array[3];
                    //热更服务器所有文件
                    serverABInfos.Add(abInfo.RelativePath, abInfo);
                }

                foreach (string localABInfoStr in localABInfos)
                {
                    if (string.IsNullOrEmpty(localABInfoStr) || string.IsNullOrWhiteSpace(localABInfoStr))
                    {
                        continue;
                    }

                    string[] array = localABInfoStr.Split('|');
                    ABInfo abInfo = new ABInfo();
                    abInfo.RelativePath = array[0];
                    abInfo.Md5 = array[1];
                    abInfo.Size = long.Parse(array[2]);
                    abInfo.FileName = array[3];
                    //本地现有文件信息
                    localABInfo.Add(abInfo.RelativePath, abInfo);
                }


                foreach (KeyValuePair<string, ABInfo> keyValuePairInfo in serverABInfos)
                {
                    //判断服务器需要的文件本地是否存在
                    if (localABInfo.ContainsKey(keyValuePairInfo.Key))
                    {
                        //老文件比对信息
                        if (keyValuePairInfo.Value.Md5 != localABInfo[keyValuePairInfo.Key].Md5)
                        {
                            needDownLoadSize = needDownLoadSize + keyValuePairInfo.Value.Size;
                            needDownloadAB.Add(keyValuePairInfo.Value);
                        }
                    }
                    else
                    {
                        //新文件需要下载
                        needDownLoadSize = needDownLoadSize + keyValuePairInfo.Value.Size;
                        needDownloadAB.Add(keyValuePairInfo.Value);
                    }
                }
            }
            else
            {
                print(localABPath+"文件不存在");
                if (File.Exists(remoteABPath))
                {
                    print(remoteABPath+"存在");
                }
                else
                {
                    print(remoteABPath+"不存在");
                }
                
                //本地比对文件不存在，下载所有文件
                string[] needRemoteABInfos = File.ReadAllLines(remoteABPath);
                foreach (string remotefiles in needRemoteABInfos)
                {
                    print("remotefiles-------------------"+remotefiles);
                    string[] array = remotefiles.Split('|');
                    ABInfo abInfo = new ABInfo();
                    abInfo.RelativePath = array[0];
                    abInfo.Md5 = array[1];
                    abInfo.Size = long.Parse(array[2]);
                    abInfo.FileName = array[3];
                    needDownLoadSize = needDownLoadSize + abInfo.Size;
                    needDownloadAB.Add(abInfo);
                }
            }

            needDownLoadCount = needDownloadAB.Count;
        }


        /// <summary>
        /// 需要下载信息
        /// </summary>
        /// <returns></returns> 
        public ref List<ABInfo> GetNeedDownLoadInfo()
        {
            return ref needDownloadAB;
        }

        /// <summary>
        /// 清理数据
        /// </summary>
        public void ClearData()
        {
            GlobalFunctions.LOG(gameObject.name + " ClearData()");
            ClearCoroutines();
            needDownLoadSize = 0;
            needDownLoadCount = 0;
            serverABInfos?.Clear();
            localABInfo?.Clear();
            needDownloadAB?.Clear();
        }

        /// <summary>
        /// 关闭所有携程
        /// </summary>
        private void ClearCoroutines()
        {
            StopAllCoroutines();
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        public void InitData()
        {
            needDownLoadSize = 0;
            needDownLoadCount = 0;
            needDownloadAB = new List<ABInfo>();
            localABInfo = new Dictionary<string, ABInfo>();
            serverABInfos = new Dictionary<string, ABInfo>();
        }
    }
}